var jweixin = require('jweixin-module');  
import Config from '@/'
import { getJsApiTicket } from '@/api/base.js'
import { hex_sha1 } from '@/utils/sha.js'
export default {  
    //判断是否在微信中    
    isWechat: function() {  
        var ua = window.navigator.userAgent.toLowerCase();  
        if (ua.match(/micromessenger/i) == 'micromessenger') {  
            //console.log('是微信客户端')  
            return true;  
        } else {  
            //console.log('不是微信客户端')  
            return false;  
        }  
    },  
	// 初始化
    initJssdk:function(callback){  
		console.log(123);
        // var url = encodeURIComponent(window.location.href.split('#')[0]);//获取当前url然后传递给后台获取授权和签名信息  
		var url = window.location.href.split('#')[0];
		getJsApiTicket().then(res=>{
			//返回需要的参数appId,timestamp,noncestr,signature等
			//注入config权限配置
			const timestamp = String(Date.parse(new Date())/1000)
			const noncestr = String(this.randomString())
			const signature = `jsapi_ticket=${res.Data.jsapi_ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}`
			const params = {
				appId: res.Data.appId,
				timestamp: timestamp,  
				nonceStr: noncestr,  
				signature: hex_sha1(signature),
			}
			
			console.log({...params,jsapi_ticket:res.Data.jsapi_ticket,url})
			
			jweixin.config({
			    debug: false,  
			    appId: params.appId,  
			    timestamp: params.timestamp,  
			    nonceStr: params.nonceStr,  
			    signature: params.signature,  
			    jsApiList: [//这里是需要用到的接口名称  
			        'checkJsApi',//判断当前客户端版本是否支持指定JS接口  
			        'onMenuShareAppMessage',//分享接口  
					'updateAppMessageShareData',
			        'getLocation',//获取位置  
			        'openLocation',//打开位置  
			        'scanQRCode',//扫一扫接口  
			        'chooseWXPay',//微信支付  
			        'chooseImage',//拍照或从手机相册中选图接口  
			        'previewImage',//预览图片接口  
			        'uploadImage',//上传图片
					'showAllNonBaseMenuItem',
					'showMenuItems',
			    ]  
			}); 
			 
			if (callback) {  
			    callback(params);  
			}  
		})
    }, 
	showAllNonBaseMenuItem:function() {
		jweixin.ready(function() {  
			jweixin.showAllNonBaseMenuItem()
		})
	},
	showMenuItems:function() {
		jweixin.ready(function() {  
			jweixin.showMenuItems({
				menuList: [
					'menuItem:share:appMessage',
					'menuItem:share:timeline',
					"menuItem:share:qq",
					"menuItem:favorite",
					'menuItem:share:QZone',
					"menuItem:profile"
				] // 要显示的菜单项，所有menu项见附录3
			})
		})
	},
    //在需要定位页面调用  
    getlocation: function(callback) {  
        if (!this.isWechat()) {  
            //console.log('不是微信客户端')  
            return;  
        }  
        // this.initJssdk(function(res) {  
            jweixin.ready(function() {  
                jweixin.getLocation({  
                    type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'  
                    success: function (res) {  
                        console.log(res);  
                    },  
                    fail:function(res){  
                        console.log(res)  
                    },  
                    complete:function(res){  
                        callback(res)  
                    }  
                });  
            });  
        // });  
    },  
    openlocation:function(data,callback){//打开位置  
        if (!this.isWechat()) {  
            //console.log('不是微信客户端')  
            return;  
        }  
        // this.initJssdk(function(res) {  
            jweixin.ready(function() {  
                jweixin.openLocation({//根据传入的坐标打开地图  
                    latitude:data.latitude,  
                    longitude:data.longitude,
					name:data.name || '',
					address:data.address || '',
					success:function(e) {
					},
					fail:function(res){
					},  
					complete:function(res){  
						console.log(res)
					    callback(res)  
					} 
                });  
            });  
        // });  
    },  
    chooseImage:function(callback){//选择图片  
        if (!this.isWechat()) {  
            //console.log('不是微信客户端')  
            return;  
        }  
        //console.log(data);  
        // this.initJssdk(function(res) {  
            jweixin.ready(function() {  
                jweixin.chooseImage({  
                    count:1,  
                    sizeType:['compressed'],  
                    sourceType:['album'],  
                    success:function(rs){  
                        callback(rs)  
                    }  
                })  
            });  
        // });  
    }, 		
	//微信分享 
	updateAppMessageShareData: function(data,callback) {
		if(!this.isWechat()) {
			return;
		}
		this.initJssdk(function(res) { 
			jweixin.ready(function(){
				jweixin.updateAppMessageShareData({
					title: data.title, // 分享标题
					desc: data.desc, // 分享描述
					link: data.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
					imgUrl:data.imgUrl, // 分享图标
					complete:function(res){
						callback(res)  
					} 
				})
			})
		})
	},
	onMenuShareAppMessage: function(data,callback) {
		if(!this.isWechat()) {
			return;
		}
		this.initJssdk(function(res) { 
			jweixin.ready(function(){
				// wx.onMenuShareAppMessage({
				// 	title: data.title, // 分享标题
				// 	desc: data.desc, // 分享描述
				// 	link: data.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				// 	imgUrl:data.imgUrl, // 分享图标
				// 	complete:function(res){
				// 		callback(res)  
				// 	} 
				// })
			})
		})
	},
    //微信支付  
    wxpay: function(data,callback) {  
        if (!this.isWechat()) {  
            //console.log('不是微信客户端')  
            return;  
        }  
        // this.initJssdk(function(res) {  
			jweixin.ready(function() {  
				jweixin.chooseWXPay({  
					timestamp: data.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符  
					nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位  
					package: data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）  
					signType: data.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'  
					paySign: data.paySign, // 支付签名  
					success: function (res) {  
						callback(res)  
						console.log('#####',res)
					},  
					fail:function(res){  
						callback(res)  
						console.log('##',res)
					},  
					complete:function(res){ 
					    callback(res)
						console.log('#',res)
					}  
				});  
			});  
        // });  
    } ,
	randomString(len) {
		len = len || 16;
	　　var $chars = 'abcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
	　　var maxPos = $chars.length;
	　　var pwd = '';
	　　for (var i = 0; i < len; i++) {
	　　　　pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
	　　}
	　　return pwd;
	},
	encodeUTF8(s) {
	  var i, r = [], c, x;
	  for (i = 0; i < s.length; i++)
	    if ((c = s.charCodeAt(i)) < 0x80) r.push(c);
	    else if (c < 0x800) r.push(0xC0 + (c >> 6 & 0x1F), 0x80 + (c & 0x3F));
	    else {
	      if ((x = c ^ 0xD800) >> 10 == 0) //对四字节UTF-16转换为Unicode
	        c = (x << 10) + (s.charCodeAt(++i) ^ 0xDC00) + 0x10000,
	          r.push(0xF0 + (c >> 18 & 0x7), 0x80 + (c >> 12 & 0x3F));
	      else r.push(0xE0 + (c >> 12 & 0xF));
	      r.push(0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
	    };
	  return r;
	},
	sha1(s) {
	  var data = new Uint8Array(this.encodeUTF8(s))
	  var i, j, t;
	  var l = ((data.length + 8) >>> 6 << 4) + 16, s = new Uint8Array(l << 2);
	  s.set(new Uint8Array(data.buffer)), s = new Uint32Array(s.buffer);
	  for (t = new DataView(s.buffer), i = 0; i < l; i++)s[i] = t.getUint32(i << 2);
	  s[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
	  s[l - 1] = data.length << 3;
	  var w = [], f = [
	    function () { return m[1] & m[2] | ~m[1] & m[3]; },
	    function () { return m[1] ^ m[2] ^ m[3]; },
	    function () { return m[1] & m[2] | m[1] & m[3] | m[2] & m[3]; },
	    function () { return m[1] ^ m[2] ^ m[3]; }
	  ], rol = function (n, c) { return n << c | n >>> (32 - c); },
	    k = [1518500249, 1859775393, -1894007588, -899497514],
	    m = [1732584193, -271733879, null, null, -1009589776];
	  m[2] = ~m[0], m[3] = ~m[1];
	  for (i = 0; i < s.length; i += 16) {
	    var o = m.slice(0);
	    for (j = 0; j < 80; j++)
	      w[j] = j < 16 ? s[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1),
	        t = rol(m[0], 5) + f[j / 20 | 0]() + m[4] + w[j] + k[j / 20 | 0] | 0,
	        m[1] = rol(m[1], 30), m.pop(), m.unshift(t);
	    for (j = 0; j < 5; j++)m[j] = m[j] + o[j] | 0;
	  };
	  t = new DataView(new Uint32Array(m).buffer);
	  for (var i = 0; i < 5; i++)m[i] = t.getUint32(i << 2);
	
	  var hex = Array.prototype.map.call(new Uint8Array(new Uint32Array(m).buffer), function (e) {
	    return (e < 16 ? "0" : "") + e.toString(16);
	  }).join("");
	  return hex;
	}
}  